package controllers

import (
	"github.com/astaxie/beego"
	"stores/models"
)

type StoresController struct {
	beego.Controller
}

type JsonRes struct {
	Code int         `json:"code"`
	Msg  string      `json:"msg"`
	Data interface{} `json:"data"`
}

func (c *StoresController) Add() {
	stoRes := c.GetString("stoRes")
	address := c.GetString("address")
	tel := c.GetString("tel")
	uptime := c.GetString("uptime")
	state := c.GetString("state")
	stores := models.Stores{
		StoRes:  stoRes,
		Address: address,
		Tel:     tel,
		Uptime:  uptime,
		State:   state,
	}
	err := models.DB.Create(&stores)
	if err != nil {
		c.Data["json"] = JsonRes{
			Code: 200,
			Msg:  "添加成功",
			Data: nil,
		}
		c.ServeJSON()
	} else {
		c.Data["json"] = JsonRes{
			Code: 200,
			Msg:  "添加成功",
			Data: nil,
		}
		c.ServeJSON()
	}
}
func (c *StoresController) List() {
	page, _ := c.GetInt("p", 1)
	size, _ := c.GetInt("s", 5)
	var count int64
	err := models.DB.Model(&models.Stores{}).Count(&count).Error
	if err != nil {
		c.Data["json"] = JsonRes{
			Code: 500,
			Msg:  "总数量查询失败",
			Data: nil,
		}
		c.ServeJSON()
		return
	}
	var stores []models.Stores
	offset := (page - 1) * size
	err = models.DB.Model(&stores).Limit(size).Offset(offset).Find(&stores).Error
	if err != nil {
		c.Data["json"] = JsonRes{
			Code: 500,
			Msg:  "查询失败",
			Data: nil,
		}
		c.ServeJSON()
	} else {
		pageData := make(map[string]interface{})
		pageData["count"] = count
		pageData["stores"] = stores
		c.Data["json"] = JsonRes{
			Code: 200,
			Msg:  "查询成功",
			Data: pageData,
		}
		c.ServeJSON()
	}
}
func (c *StoresController) Update() {
	id, _ := c.GetInt("id")
	stoRes := c.GetString("stoRes")
	storse := models.Stores{
		StoRes: stoRes,
	}
	err := models.DB.Where("id = ?", id).Updates(storse).Error
	if err != nil {
		c.Data["json"] = JsonRes{
			Code: 500,
			Msg:  "修改失败",
			Data: nil,
		}
		c.ServeJSON()
	} else {
		c.Data["json"] = JsonRes{
			Code: 200,
			Msg:  "修改成功",
			Data: nil,
		}
		c.ServeJSON()
	}
}
